package dao;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter(filterName = "RoleFilter", urlPatterns = "/*")
public class RoleFilter implements Filter {
    public void destroy() {
    }


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String pathStr = request.getRequestURI();

        boolean isChain = false;
        if (pathStr.endsWith(".js") || pathStr.endsWith(".css")
                || pathStr.endsWith(".jpg") || pathStr.endsWith("user.jsp")
                || pathStr.endsWith(".png") || pathStr.endsWith("LoginServlet")
                || pathStr.endsWith("LoginSuccessServlet") || pathStr.endsWith("ChengxuServlet")
                || pathStr.endsWith("UsersSelectServlet") || pathStr.endsWith("OrderbiaoServlet")
                || pathStr.endsWith("InsertOrderbiaoServlet") || pathStr.endsWith("OrderbiaoidServlet")
                || pathStr.endsWith("wjmm.jsp")
        ) {
            isChain = true;
        } else {
            //验证是否登录
            ;

//            HttpSession session = request.getSession();
//            if (session.getAttribute("userEntity") != null) {
//                isChain=true;
//            }
            String tokenStr = "";
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {

                for (int i = 0; i < cookies.length; i++) {
                    if (cookies[i].getName().equals("userToken")) {
                        tokenStr = cookies[i].getValue();
                    }
                }


                if (JedisUtils.getString(tokenStr) != null) {
                    isChain = true;
                }
            }
        }
        System.out.println(pathStr + "=" + isChain);
        if (isChain) {
            chain.doFilter(req, resp);
        } else {
            response.sendRedirect(request.getContextPath() + "/user.jsp");
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
